package fr.rinie.android_first_step;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class FishAdapter extends ArrayAdapter<FishContainer.Fish> {
    private final Activity activity;
    private final List<FishContainer.Fish> fishList;

    public FishAdapter(Activity act, int resource, List<FishContainer.Fish> arrayList) {
        super(act, resource, arrayList);
        this.activity = act;
        this.fishList = arrayList;
    }

    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listfish, null);
            holder = new ViewHolder();
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        if ((fishList == null) || ((position + 1) > fishList.size())) {
            return view;
        }

        FishContainer.Fish fish = getItem(position);
        holder.name = (TextView) view.findViewById(R.id.name);
        holder.commonName = (TextView) view.findViewById(R.id.commonName);

        if (holder.name != null && null != fish.scientificName
                && fish.scientificName.trim().length() > 0) {
            holder.name.setText(fish.scientificName);
        }
        if (holder.commonName != null && null != fish.commonName) {
            holder.commonName.setText(fish.getFormatedCommonName("Nom commun: "));
        }

        return view;
    }

    public class ViewHolder {

        public TextView name;
        public TextView commonName;
    }
}